<template>
  <div class="bg-white dark:bg-zinc-900 sticky top-0 left-0 z-10 duration-500">
    <ul class="relative flex overflow-x-auto p-1 text-xs text-zinc-600 overflow-hidden" ref="ulTarget">
      <!--  滑块-->
      <li ref="sliderTarget" :style="sliderStyle"
          class="absolute h-[22px] bg-zinc-900 dark:bg-zinc-800 rounded-lg duration-200"></li>
      <!--  汉堡-->
      <li class="fixed top-0 right-[-1px] h-4 px-1 flex items-center bg-white dark:bg-zinc-800 z-20 shadow-l-white dark:shadow-l-zinc">
        <mine-svg-icon class="w-1.5 h-1.5" name="hamburger" @click="onShowPopUp"></mine-svg-icon>
      </li>
      <!-- items -->
      <li v-for="(item,index) in $store.getters.categories"
          :key="index"
          class="shrink-0 px-1.5 py-0.5 z-10 duration-200 last:mr-4"
          :class="{'text-zinc-100':$store.getters.currentCategoryIndex === index}"
          @click="onItemClick(item)"
          :ref="setItemRef">
        {{ item.name }}
      </li>
    </ul>
    <mine-popup v-model="isVisable">
      <mine-menu @onItemClick="onItemClick"></mine-menu>
    </mine-popup>
  </div>
</template>

<script setup>
import {onBeforeUpdate, ref, watch} from "vue";
import {useScroll} from "@vueuse/core";
import MineMenu from '@/views/main/components/menu/index.vue'
import {useStore} from "vuex";

const store = useStore()

/**
 * 滑块
 * @type {Ref<UnwrapRef<{transform: string, width: string}>>}
 */
const sliderStyle = ref({
  transform: 'translateX(0px)',
  width: '52px'
})

/**
 * 获取所有的item元素
 */
let itemRefs = []
const setItemRef = (el) => {
  if (el) {
    itemRefs.push(el)
  }
}

/**
 * 获取ul元素
 * @type {null}
 */
const ulTarget = ref(null)

/**
 * 通过vueuse -> useScroll获取响应式的scroll滚动距离
 */
const {x: ulScrollLeft} = useScroll(ulTarget)

/**
 * watch监听 getters时，需要传递函数
 */
watch(() => store.getters.currentCategoryIndex, (val) => {
  const {left, width} = itemRefs[val].getBoundingClientRect()
  sliderStyle.value = {
    //滑块的位置 = ul横向滚动的位置 + 当前元素的left - ul的padding
    transform: `translateX(${ulScrollLeft.value + left - 10}px)`,
    width: `${width}px`
  }
})

const onItemClick = (item) => {
  store.commit('app/changeCurrentCategory', item)
  isVisable.value = false
}


const isVisable = ref(false);

const onShowPopUp = () => {
  isVisable.value = true
}

/**
 * 数据改变之后 ，DOM变化前
 */
onBeforeUpdate(() => {
  itemRefs = []
})
</script>
